import pd from '/api/productData.js';
import cd from '/api/cartData.js'
import hs from '/components/head-search.js';
import rfb from '/components/right-fixed-bar.js';
class Pager {
    constructor(pageDataSize, key) {
        this.container = document.querySelector(".plist")
        this.pages = document.querySelector(".pages");
        [this.firstPage, this.prePage, this.numPage, this.nextPage, this.lastPage] = this.pages.children;
        this.pageDataSize = pageDataSize;
        this.currIndex = 0;
        this.init(key);
    }
    init(key) {
        pd.getByKey(key, data => {
            this.data = data;
            // console.log(data);
            if (data.length != 0) {
                for (let i = 0; i < data.length; i++) {
                    const p = data[i];
                    // console.log(p.name.match('京东超市'));
                    const b = p.name.match('京东超市') != null;
                    const c = p.shop.match('自营') != null;
                    const k = Math.random() > 0.5 ? '赠' : (Math.random() > 0.5 ? '2件8折' : '2件9折');
                    let str = '';
                    for (let i = 0; i < Math.ceil(this.data.length / this.pageDataSize); i++) {
                        str += ` <span${i == this.currIndex ? ' class="curr"' : ''}>${i + 1}</span>`;
                    }
                    this.numPage.innerHTML = str;
                    this.generateList(this.currIndex).setOnClick();
                    // this.container.style.height = this.container.children[0].offsetHeight * this.pageDataSize + "px";
                }

            } else {
                location.href = '/index.html';
            }
        })
    }
    generateList(index) {
        let str = "";

        this.data.slice(index * this.pageDataSize, index * this.pageDataSize + this.pageDataSize).forEach(p => {
            const b = p.name.match('京东超市') != null;
            const c = p.shop.match('自营') != null;
            const k = Math.random() > 0.5 ? '赠' : (Math.random() > 0.5 ? '2件8折' : '2件9折');
            str += `
            <li>
                <div class="gl-i-wrap">
                    <div class="p-img">
                        <a target="_blank" href="/pages/detial.html?pid=${p.pid}&discount=${k}">
                            <img width="220" height="220" src="${p.imgsrc}">
                        </a>
                        <div  class="picon"></div>
                    </div>
                    <div class="p-price">
                        <strong>
                            <em>￥</em><i>${p.price}</i>
                        </strong>
                        <span class="price-plus-1 ${p.price_plus.length>0?"":"hide"}">
                            <em>${p.price_plus}</em>
                            <i></i>
                        </span>
                    </div>
                    <div class="p-name p-name-type-2">
                        <a target="_blank" href="/pages/detial.html?pid=${p.pid}&discount=${k}">
                            <em>
                                <span class="p-tag ${b?"":"hide"}" style="background-color:#c81623">京东超市</span>
                                ${b?p.name.replace('京东超市',''):p.name}
                            </em>
                        </a>
                    </div>
                    <div class="p-commit">
                        <strong>
                            <a>${parseInt(p.comments/10000)}万+</a>条评价
                        </strong>
                    </div>
                    <div class="p-shop">
                        <span class="J_im_icon">
                            <a target="_blank" class="curr-shop hd-shopname" href="./list.html?shop=${p.shop}" >${p.shop}</a>
                            <b class="im-02"></b>
                        </span>
                    </div>
                    <div class="p-icons">
                        ${c?'<i class="goods-icons J-picon-tips J-picon-fix">自营</i>':""}
                        <i class="goods-icons4 J-picon-tips" style="border-color:#4d88ff;color:#4d88ff;">放心购</i>
                        <i class="goods-icons4 J-picon-tips">${k}</i>
                    </div>
                    <div class="p-operate">
                        <a class="p-o-btn contrast J_contrast contrast" href="javascript:;"><i></i>对比</a>
                        <a class="p-o-btn focus  J_focus" href="javascript:;"><i></i>关注</a>
                        <a class="p-o-btn addcart" href="javascript:;" data-id=${p.pid}><i></i>加入购物车</a>
                    </div>
                </div>
            </li>
            
            `;
        });
        this.container.innerHTML = str;
        /* flext 布局 补位 */
        if (4 - this.data.slice(index * this.pageDataSize, index * this.pageDataSize + this.pageDataSize).length % 4 != 4) {
            for (let i = 0; i < 4 - this.data.slice(index * this.pageDataSize, index * this.pageDataSize + this.pageDataSize).length % 4; i++) {
                str += `<mark></mark>`;
            }
        }
        // console.log(str);
        $('.plist').html(str);
        $('.addcart').off('click').on('click', function(e) {
            cd.add($(this).data('id'));
            rfb.intoCart($(this).parent().parent().find('.p-img img'), $(this).offset());
        })
        return this;
    }
    setOnClick() {
        // 页数span
        this.aSpans = this.numPage.querySelectorAll("span");
        this.aSpans.forEach((el, i) => {
            el.onclick = () => {
                this.generateList(i).setState(el);
            }
        })
        // 首页
        this.firstPage.onclick = () => {
            this.generateList(0).setState(this.aSpans[0])
        }
        // 尾页
        this.lastPage.onclick = () => {
            this.generateList((this.aSpans.length - 1)).setState(this.aSpans[this.aSpans.length - 1]);
        }
        // 上一页
        this.prePage.onclick = () => {
            this.setPreNext(false);
        }
        // 下一页
        this.nextPage.onclick = () => {
            this.setPreNext(true);
        }
    }
    setState(obj) {
        this.pages.querySelector(".curr").removeAttribute("class");
        obj.className = "curr";
    }
    // 设置上下页
    setPreNext(b) {
        let item = b ? this.numPage.querySelector(".curr").nextElementSibling : this.numPage.querySelector(".curr").previousElementSibling;
        if (item) {
            this.generateList(+item.innerText - 1).setState(item);
        }
    }
}
(() => {
    /* 加载顶部导航栏 */
    $('.header-top-nav-wrap').load('/components/head-nav.html');
    /* 加载头部搜索框 并对样式进行修改 */
    $('.head').load('/components/head-search.html', function() {
        /* 隐藏位置下拉菜单 */
        $('.logo_dropdown').hide();
        /* 更改样式 */
        $('.search-bar').css('border-color', "#E12118").find('.search-btn').css('background-color', "#E12118");
        $('.search-key').attr('placeholder', getKey());
        $('.search-btn').on('click', function() {
            const key = $('.search-key').val();

            // console.log(key ? "q=" + key : "title=" + $('.search-key').attr('placeholder'));
            location.href = '/pages/list.html?' + (key ? "q=" + key : "title=" + $('.search-key').attr('placeholder'));
        })
    });

    /* 根据关键字动态改变title */
    $('.bottom-footer-wrap').load('/components/bottom-footer.html');
    $('.right-bar').load('/components/right-fixed-bar.html');
    const key = (location.search).split('?')[1];
    listRender(key);

})()



function getKey() {
    return decodeURIComponent(location.search.split('=')[1]);
}

function listRender(key) {
    // console.log(key);
    $('title').text(getKey())
    new Pager(24, key);
    // // const params = new URLSearchParams(location.search);
    // pd.getByKey(key + '&_limit=30', data => {
    //     if (data.length != 0) {
    //         let str = ``;
    //         for (let i = 0; i < data.length; i++) {
    //             const p = data[i];
    //             // console.log(p.name.match('京东超市'));
    //             const b = p.name.match('京东超市') != null;
    //             const c = p.shop.match('自营') != null;
    //             const k = Math.random() > 0.5 ? '赠' : (Math.random() > 0.5 ? '2件8折' : '2件9折');
    //             str += `
    //                 <li>
    //                     <div class="gl-i-wrap">
    //                         <div class="p-img">
    //                             <a target="_blank" href="/pages/detial.html?pid=${p.pid}&discount=${k}">
    //                                 <img width="220" height="220" src="${p.imgsrc}">
    //                             </a>
    //                             <div  class="picon"></div>
    //                         </div>
    //                         <div class="p-price">
    //                             <strong>
    //                                 <em>￥</em><i>${p.price}</i>
    //                             </strong>
    //                             <span class="price-plus-1 ${p.price_plus.length>0?"":"hide"}">
    //                                 <em>${p.price_plus}</em>
    //                                 <i></i>
    //                             </span>
    //                         </div>
    //                         <div class="p-name p-name-type-2">
    //                             <a target="_blank" href="/pages/detial.html?pid=${p.pid}&discount=${k}">
    //                                 <em>
    //                                     <span class="p-tag ${b?"":"hide"}" style="background-color:#c81623">京东超市</span>
    //                                     ${b?p.name.replace('京东超市',''):p.name}
    //                                 </em>
    //                             </a>
    //                         </div>
    //                         <div class="p-commit">
    //                             <strong>
    //                                 <a>${parseInt(p.comments/10000)}万+</a>条评价
    //                             </strong>
    //                         </div>
    //                         <div class="p-shop">
    //                             <span class="J_im_icon">
    //                                 <a target="_blank" class="curr-shop hd-shopname" href="./list.html?shop=${p.shop}" >${p.shop}</a>
    //                                 <b class="im-02"></b>
    //                             </span>
    //                         </div>
    //                         <div class="p-icons">
    //                             ${c?'<i class="goods-icons J-picon-tips J-picon-fix">自营</i>':""}
    //                             <i class="goods-icons4 J-picon-tips" style="border-color:#4d88ff;color:#4d88ff;">放心购</i>
    //                             <i class="goods-icons4 J-picon-tips">${k}</i>
    //                         </div>
    //                         <div class="p-operate">
    //                             <a class="p-o-btn contrast J_contrast contrast" href="javascript:;"><i></i>对比</a>
    //                             <a class="p-o-btn focus  J_focus" href="javascript:;"><i></i>关注</a>
    //                             <a class="p-o-btn addcart" href="javascript:;" data-id=${p.pid}><i></i>加入购物车</a>
    //                         </div>
    //                     </div>
    //                 </li>
    //                 `;
    //         }
    //         // console.log(data.length % 4);
    //         /* flext 布局 补位 */
    //         for (let i = 0; i < 4 - data.length % 4; i++) {
    //             str += `<mark></mark>`;
    //         }
    //         // console.log(str);
    //         $('.plist').html(str);
    //         $('.addcart').off('click').on('click', function(e) {
    //             cd.add($(this).data('id'));
    //             rfb.intoCart($(this).parent().parent().find('.p-img img'), $(this).offset());
    //         })
    //     } else {
    //         location.href = '/index.html';
    //     }
    // })
}